/**
 * 注册路由
 */

import React, { useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import { Switch, Route, Redirect } from 'react-router-dom'
import Cookies from 'js-cookie'

import { getUserByCookie, getMsgList } from '../../api/index'
import DaShenInfo from '../dashen_info/dashenInfo'
import LaoBanInfo from '../laoban_info/laobanInfo'
import LaoBan from './laoban'
import DaShen from './dashen'
import NotFound from '../../components/notFound'
import Person from './person'
import Chat from '../chat/chat'
import Message from './message'
import { NavBar } from 'antd-mobile';
import NavFooter from './nav-footer'

import { socketInit } from './socketClient'

const navList = [ // 包含所有导航组件的相关信息数据
  {
    path: '/laoban', // 路由路径
    component: LaoBan,
    title: '大神列表',
    icon: 'dashen',
    text: '大神',
  },
  {
    path: '/dashen', // 路由路径
    component: DaShen,
    title: '老板列表',
    icon: 'laoban',
    text: '老板',
  },
  {
    path: '/message', // 路由路径
    component: Message,
    title: '消息列表',
    icon: 'message',
    text: '消息',
  },
  {
    path: '/personal', // 路由路径
    component: Person,
    title: '用户中心',
    icon: 'personal',
    text: '个人',
  }
]

function Main(props) {
  const { user, history, location,unReadCount } = props
  const pathname = location.pathname
  const userInfo = user.userInfo || {}
  const curNav = useMemo(() => getCurNav(pathname), [pathname])
  function getCurNav(pathName) {
    let temp = navList.find(i => i.path == pathName);
    return temp
  }

  if (curNav) {
    if (userInfo.type == "dashen") {
      navList[0].hidden = true
      navList[1].hidden = false
    } else if (userInfo.type == "laoban") {
      navList[1].hidden = true
      navList[0].hidden = false
    }
  }

  // 用户已经登陆好了
  useEffect(() => {
    if (userInfo._id) {
      console.log(userInfo._id, "用户_id得到,开始连接websocket");
      getMsgList().then((res) => {
        const { chatMsg } = res
        let unReadCount = chatMsg.filter(i => !i.read && i.to ==userInfo._id ).length
        props.dispatch({ type: "Receive_Msg_List", data: {...res, unReadCount} })
      }).catch((err) => {
        alert(err, "获取消息列表失败")
      });
      socketInit(props.dispatch, userInfo._id)
    }
  }, [userInfo._id])

  useEffect(() => {
    if (pathname == "/") {
      findPath()
    }
  }, [pathname])

  useEffect(() => {
    findPath()
  }, [user])

  function findPath(params) {
    if (userInfo && userInfo.type == "dashen") {
      if (userInfo.header) {
        history.push("/dashen")
      } else {
        history.push("/dasheninfo")
      }
    } else if (userInfo && userInfo.type == "laoban") {
      if (userInfo.header) {
        history.push("/laoban")
      } else {
        history.push("/laobaninfo")
      }
    } else {
      // 使用cookie自动登陆
      const userId = Cookies.get("user_id");
      if (userId) {
        getUserByCookie().then((result) => {
          props.dispatch({ type: "Update_User_Info", data: result })
        }).catch((err) => {
          alert(err)
          props.history.push("/login")
        });
      } else {
        props.history.push("/login")
      }
    }
  }

  return (
    <div>
      {curNav && <NavBar>{curNav.title}</NavBar>}
      <div style={{ minHeight: 300 }}>
        <Switch>
          <Route path="/laobaninfo" component={LaoBanInfo} />
          <Route path="/dashenInfo" component={DaShenInfo} />
          <Route path="/chat/:userId" component={Chat} />
          {
            navList.map(i => {
              return <Route {...i} key={i.path} />
            })
          }
          <Route path="/notfound" component={NotFound} />
          <Redirect to="/notfound" />
        </Switch>
      </div>
      {curNav && <NavFooter navList={navList} unReadCount={unReadCount}>{curNav.title}</NavFooter>}
    </div>
  );
}

export default connect(state => ({ user: state.user, unReadCount: state.chat.unReadCount }))(Main)
